import decimal
from datetime import timedelta, datetime

from flask import jsonify, request
from flask_jwt_extended import get_jwt_identity
from sqlalchemy import func, or_

from app import db
from app.models import User
from app.models.commission import CommissionLog, WithdrawLog
from app.services.decorators import admin_required

from . import admin_blueprint


@admin_blueprint.route("/list", methods=["GET"])
@admin_required
def commission_list():
    user_id = request.args.get("user_id", type=int)
    page = request.args.get("page", default=1, type=int)
    page_size = request.args.get("page_size", default=10, type=int)

    if not user_id:
        return jsonify({"error": "缺少 user_id"}), 400

    query = CommissionLog.query.filter_by(to_user_id=user_id).order_by(CommissionLog.created_at.desc())

    total = query.count()
    records = query.offset((page - 1) * page_size).limit(page_size).all()

    from_user_ids = [r.from_user_id for r in records]
    users = User.query.filter(User.user_id.in_(from_user_ids)).all()  # 注意这里改成 user_id
    user_map = {u.user_id: u.nickname for u in users}  # 这里也改

    data = []
    for r in records:
        data.append({
            "order_id": r.order_id,
            "from_user_id": r.from_user_id,
            "from_user_name": user_map.get(r.from_user_id, ""),
            "amount": float(r.amount),
            "rate": float(r.rate),
            "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })

    # 全部佣金总额（to_user_id 对应用户）
    total_amount_all = db.session.query(db.func.sum(CommissionLog.amount)) \
                           .filter(CommissionLog.to_user_id == user_id).scalar() or 0

    return jsonify({
        "total": total,
        "total_amount": float(total_amount_all),  # 全部历史总收益
        "list": data
    })


@admin_blueprint.route("/details", methods=["GET"])
@admin_required
def get_commission_summary():
    user_id = request.args.get("user_id", type=int)
    if not user_id:
        return jsonify({"error": "缺少 user_id"}), 400

    now = datetime.now()

    # 今日
    start_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end_today = now

    # 昨日
    start_yesterday = start_today - timedelta(days=1)
    end_yesterday = start_today

    # 本月
    start_this_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

    # 上月
    first_day_last_month = (start_this_month - timedelta(days=1)).replace(day=1)
    last_day_last_month = start_this_month - timedelta(seconds=1)

    def sum_commission(start_time, end_time):
        from sqlalchemy import func
        return CommissionLog.query.with_entities(func.coalesce(func.sum(CommissionLog.amount), 0)) \
            .filter(
            CommissionLog.to_user_id == user_id,
            CommissionLog.created_at >= start_time,
            CommissionLog.created_at < end_time
        ).scalar()

    result = {
        "today": float(sum_commission(start_today, end_today)),
        "yesterday": float(sum_commission(start_yesterday, end_yesterday)),
        "this_month": float(sum_commission(start_this_month, end_today)),
        "last_month": float(sum_commission(first_day_last_month, last_day_last_month))
    }

    return jsonify({
        "code": 1,
        "data": result
    })


@admin_blueprint.route("/balance", methods=["GET"])
@admin_required
def get_balance():
    user_info = get_jwt_identity()  # 取出登录信息，类型是dict

    user_id = None
    if isinstance(user_info, dict):
        user_id = user_info.get('user_id')
    else:
        user_id = user_info  # 如果是简单ID

    if not user_id:
        return jsonify({"code": 0, "msg": "未获取到用户ID"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"code": 0, "msg": "用户不存在"}), 404

    return jsonify({
        "code": 1,
        "balance": str(user.balance)  # 转成字符串避免序列化错误
    })


@admin_blueprint.route("/apply_withdraw", methods=["POST"])
@admin_required
def apply_withdraw():
    user_info = get_jwt_identity()  # 取出登录信息，类型是dict

    user_id = None
    if isinstance(user_info, dict):
        user_id = user_info.get('user_id')
    else:
        user_id = user_info

    if not user_id:
        return jsonify({"code": 0, "msg": "未获取到用户ID"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"code": 0, "msg": "用户不存在"}), 404

    data = request.json
    amount = data.get('amount')
    account = data.get('account')
    realname = data.get('realname')  # 如果需要实名

    if not amount or not account or not realname:
        return jsonify({"msg": "缺少必要参数"}), 400

    try:
        amount = decimal.Decimal(str(amount))
        if amount <= 0:
            return jsonify({"msg": "提现金额必须大于0"}), 400
    except:
        return jsonify({"msg": "提现金额格式错误"}), 400

    # 查询用户余额（假设User有balance字段）
    user = User.query.get(user_id)
    if not user:
        return jsonify({"msg": "用户不存在"}), 404

    if user.balance < amount:
        return jsonify({"msg": "余额不足"}), 400

    # 创建提现记录
    withdraw_log = WithdrawLog(
        user_id=user_id,
        amount=amount,
        status='pending',
        method='alipay',  # 这里写死支付宝提现
        account=account,
        remark=f'实名：{realname}'
    )
    db.session.add(withdraw_log)

    # 扣除余额（假设直接扣除）
    user.balance -= amount

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": "服务器错误，提交失败"}), 500

    return jsonify({"msg": "提现申请提交成功"}), 200


# 修改提现账号（如支付宝）
@admin_blueprint.route("/profile/account", methods=["POST"])
@admin_required
def update_withdraw_account():
    user_info = get_jwt_identity()
    user_id = user_info.get('user_id') if isinstance(user_info, dict) else user_info

    data = request.get_json()
    account = data.get('account')
    realname = data.get('realname')

    if not account or not realname:
        return jsonify({"msg": "缺少账号或实名信息"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"msg": "用户不存在"}), 404

    user.withdraw_account = account
    user.realname = realname

    try:
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({"msg": "保存失败"}), 500

    return jsonify({"msg": "提现账号更新成功"})


# 管理员查看所有用户提现申请（带分页）
@admin_blueprint.route('/withdraw/all', methods=['GET', 'OPTIONS'])
@admin_required
def list_all_withdraws():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '', type=str)
    query = WithdrawLog.query.order_by(WithdrawLog.created_at.desc())

    if search:
        query = query.filter(
            or_(
                WithdrawLog.account.like(f'%{search}%'),
                WithdrawLog.user_id == int(search) if search.isdigit() else False
            )
        )
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    items = []
    for item in pagination.items:
        user = User.query.get(item.user_id)
        items.append({
            **item.to_dict(),
            "nickname": user.nick_name if user else ""
        })

    return jsonify({
        "code": 0,
        "msg": "获取成功",
        "data": {
            "items": items,
            "total": pagination.total,
            "page": pagination.page,
            "pages": pagination.pages
        }
    })


# 管理员审核提现（通过或拒绝）
@admin_blueprint.route('/withdraw/approve', methods=['POST'])
@admin_required
def approve_withdraw():
    data = request.get_json()
    withdraw_id = data.get('id')
    status = data.get('status')  # 'approved' or 'rejected'

    if status not in ['approved', 'rejected']:
        return jsonify({"msg": "非法状态"}), 400

    withdraw = WithdrawLog.query.get(withdraw_id)
    if not withdraw:
        return jsonify({"msg": "提现记录不存在"}), 404

    if withdraw.status != 'pending':
        return jsonify({"msg": "该记录已审核"}), 400

    withdraw.status = status
    if status == 'rejected':
        # 驳回则退回金额
        user = User.query.get(withdraw.user_id)
        user.balance += withdraw.amount
    elif status == 'approved':
        pass
    try:
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({"msg": "更新失败"}), 500

    return jsonify({"msg": f"提现已{status}"})


# 管理员修改用户余额
@admin_blueprint.route('/user/balance/update', methods=['POST'])
@admin_required
def update_user_balance():
    data = request.get_json()
    user_id = data.get('user_id')
    amount = data.get('amount')  # 支持正负数
    remark = data.get('remark', '')

    if user_id is None or amount is None:
        return jsonify({"msg": "参数缺失"}), 400

    try:
        amount = decimal.Decimal(str(amount))
    except:
        return jsonify({"msg": "金额格式错误"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"msg": "用户不存在"}), 404

    user.balance += amount

    try:
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({"msg": "修改失败"}), 500

    return jsonify({"msg": "余额修改成功"})


# 获取列表（分页 + 搜索）
@admin_blueprint.route('/commission/list', methods=['GET'])  # /api/admin/commission
def list_commissions():
    search = request.args.get('search', '', type=str)
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    query = CommissionLog.query.order_by(CommissionLog.created_at.desc())

    if search and search.isdigit():
        query = query.filter(
            or_(
                CommissionLog.from_user_id == int(search),
                CommissionLog.to_user_id == int(search)
            )
        )

    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    items = [item.to_dict() for item in pagination.items]

    return jsonify({
        "code": 0,
        "data": {
            "items": items,
            "total": pagination.total
        }
    })


# 新增
@admin_blueprint.route('/commission/add', methods=['POST'])  # /api/admin/commission
def create_commission():
    data = request.get_json()
    try:
        commission = CommissionLog(
            order_id=data['order_id'],
            from_user_id=data['from_user_id'],
            to_user_id=data['to_user_id'],
            amount=data['amount'],
            rate=data['rate'],
            created_at=datetime.datetime.now()
        )
        db.session.add(commission)
        db.session.commit()
        return jsonify({"code": 0, "message": "添加成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"code": 1, "message": f"添加失败: {str(e)}"}), 400


# 修改
@admin_blueprint.route('/commission/update/<int:commission_id>', methods=['PUT'])  # /api/admin/commission/1
def update_commission(commission_id):
    data = request.get_json()
    commission = CommissionLog.query.get(commission_id)
    if not commission:
        return jsonify({"code": 1, "message": "记录不存在"}), 404

    try:
        commission.order_id = data['order_id']
        commission.from_user_id = data['from_user_id']
        commission.to_user_id = data['to_user_id']
        commission.amount = data['amount']
        commission.rate = data['rate']
        db.session.commit()
        return jsonify({"code": 0, "message": "更新成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"code": 1, "message": f"更新失败: {str(e)}"}), 400


# 删除
@admin_blueprint.route('/commission/delete/<int:commission_id>', methods=['DELETE'])  # /api/admin/commission/1
def delete_commission(commission_id):
    commission = CommissionLog.query.get(commission_id)
    if not commission:
        return jsonify({"code": 1, "message": "记录不存在"}), 404

    try:
        db.session.delete(commission)
        db.session.commit()
        return jsonify({"code": 0, "message": "删除成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"code": 1, "message": f"删除失败: {str(e)}"}), 400
